<?php

namespace app\shop\model\user;

use wanyue\traits\ModelTrait;
use wanyue\basic\BaseModel;
use think\facade\Session;

/**
 * Class SystemAdmin
 * @package app\admin\model\system
 */
class User extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'uid';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'user';

    use ModelTrait;

    /**
     * 用户登陆
     * @param $account
     * @param $pwd
     * @return bool
     */
    public static function login($account)
    {
        $adminInfo = self::where('account|phone',$account)->find();
        if (!$adminInfo) return self::setErrorInfo('登陆的账号不存在!');
        //if (!$adminInfo['status']) return self::setErrorInfo('该账号已被关闭!');
        if (!$adminInfo['isshop']) return self::setErrorInfo('该账号还未开通店铺!');
        self::setLoginInfo($adminInfo);
        return true;
    }

    /**
     *  保存当前登陆用户信息
     */
    public static function setLoginInfo($adminInfo)
    {
        Session::set('shopId', $adminInfo['uid']);
        Session::set('shopInfo', $adminInfo->toArray());
        Session::save();
    }

    /**
     * 清空当前登陆用户信息
     */
    public static function clearLoginInfo()
    {
        Session::delete('shopId');
        Session::delete('shopInfo');
        Session::save();
    }

    /**
     * 检查用户登陆状态
     * @return bool
     */
    public static function hasActive()
    {
        return Session::has('shopId') && Session::has('shopInfo');
    }

    /**
     * 获得登陆用户信息
     * @return mixed
     * @throws \Exception
     */
    public static function activeInfoOrFail()
    {
        $adminInfo = Session::get('shopInfo');
        //if (!$adminInfo) exception('请登陆');
        //if (!$adminInfo['status']) exception('该账号已被关闭!');
        return $adminInfo;
    }

    /**
     * 获得登陆用户Id 如果没有直接抛出错误
     * @return mixed
     * @throws \Exception
     */
    public static function activeIdOrFail()
    {
        $adminId = Session::get('shopId');
        if (!$adminId) exception('访问用户为登陆登陆!');
        return $adminId;
    }

    /**
     * 获得有效管理员信息
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public static function getValidInfoOrFail($id)
    {
        $adminInfo = self::get($id);
        //if (!$adminInfo) exception('用户不能存在!');
        //if (!$adminInfo['status']) exception('该账号已被关闭!');
        return $adminInfo;
    }

    /**
     * @param $where
     * @return array
     */
    public static function systemPage($where)
    {
        $model = new self;
        if ($where['name'] != '') $model = $model->where('account|real_name', 'LIKE', "%$where[name]%");
        $model = $model->where('is_del', 0);
        return self::page($model,  $where);
    }
}